package cen.tms.ggtour;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import cen.tms.ggtour.data.DataManager;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class PreviewTour extends MapActivity{
	//Jonathan Vars
	ListView locations;
	Button eventsButton;
	UpdateLocationList updateMyList;
	int locID = -1;
	View infoHolder = null;
	ListView events = null;
	CursorAdapter campusadapter= getAdapter();
	//end Jonathan Vars
	
	SlidingDrawer notifDrawer;

	MapView mapView;
	MapController mc;
	GeoPoint p, p2;
    private MyLocationOverlay locationoverlay;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Jonathan Code
        setContentView(R.layout.mapview);
        eventsButton = (Button) findViewById(R.id.events_button);
        notifDrawer = (SlidingDrawer) findViewById(R.id.notifications);
        
        notifDrawer.lock();     //manually lock for now, as the check for events never gets called
        
        locations = (ListView)findViewById(R.id.mapEvents);
        locations.setOnItemClickListener(new OnItemClickListener(){
        	//detects clicks on listView, opens display activity
     		public void onItemClick(AdapterView<?> parent, View subview, int position, long rowid) {
     			locID = DataManager.getID(((Cursor)locations.getAdapter().getItem(position)));
     			showDialog(1);
     		}
        });
        //start listAdapter task
        locations.setAdapter(getAdapter(null));
        startManagingCursor(((CursorAdapter) locations.getAdapter()).getCursor());
        //end Jonathan Code
        
        TextView title = (TextView) findViewById(android.R.id.title);
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/book_antiqua.ttf");
        title.setTypeface(tf);
        title.setText("Preview Tour");
        
        mapView = (MapView)findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(false);
        mc = mapView.getController();
        
        locationoverlay = new MyLocationOverlay(this, mapView);
        
        mapView.getOverlays().add(locationoverlay);
        
        locationoverlay.enableCompass();
        locationoverlay.enableMyLocation();
        locationoverlay.runOnFirstFix(new Runnable() {
            public void run() {
                mc.animateTo(locationoverlay.getMyLocation());
            }
        });
        
        mc.setZoom(17);
        
        mapView.invalidate();
    }
	 @Override
		protected void onResume() {
		 	updateMyList = new UpdateLocationList(this);
		 	updateMyList.execute();
			super.onResume();
		}

	@Override
	protected void onPause() {
		updateMyList.cancel(false);
		super.onPause();
		locationoverlay.disableCompass();
		locationoverlay.disableMyLocation();
	}
	
	public void onTitleBackClick(View view) {
		this.onBackPressed();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	protected Dialog onCreateDialog(int id) {
		Dialog beta = null;
		switch(id){
		  case 1:
			beta = new Dialog(this);
			beta.setContentView(R.layout.locationview);
			infoHolder = getLayoutInflater().inflate(R.layout.locationinfo, null);
			events = (ListView)beta.findViewById(R.id.mapEvents);
			events.addHeaderView(infoHolder);
			events.setAdapter(campusadapter);
			events.setOnItemClickListener(new OnItemClickListener(){
	        	//detects clicks on listView, opens display activity
	     		public void onItemClick(AdapterView<?> parent, View subview, int position, long rowid) {
	     			if(position >= 1){
  	     			  //Jonathan Code
	     			  //store _id of Event into bundle
	     			  Bundle thisEvent = new Bundle();
	     			  thisEvent.putInt("_id", DataManager.getID(((Cursor) campusadapter.getItem(position-1))));
	     			  //place bundle into Intent
	     			  Intent displayEvent = new Intent("cen.tms.ggtour.DISPLAY_EVENT");
	     			  displayEvent.putExtras(thisEvent);
	     			  //start display Activity
	     			  startActivity(displayEvent);
	     			  //end Jonathan Code
	     			}
	     		}
	        });
			break;
	 	  default:
			beta = new Dialog(this);
			beta.setContentView(R.layout.beta);
			break;
		}
		return beta;
	}
	protected void onPrepareDialog(int id, Dialog beta){
		switch(id){
		case 1:
			Cursor location = DataManager.getInstance(getApplicationContext()).getLocation(locID);
			
			TextView info = (TextView)infoHolder.findViewById(R.id.locInfo);
			if(location.moveToFirst()){
		      beta.setTitle(DataManager.getName(location));
			  info.setText(DataManager.getInfo(location));
			  
			  stopManagingCursor(campusadapter.getCursor());
			  campusadapter.changeCursor(DataManager.getInstance(getApplicationContext()).getEvents(null, null, DataManager.getName(location), null ));
			  startManagingCursor(campusadapter.getCursor());
			}
			else{
			  beta.setTitle("");
			  info.setText("");
			}
			location.close();
			break;
		default:
			break;
		}
	}
	
	private CursorAdapter getAdapter(ArrayList<Integer> input){
		return new CursorAdapter(this, DataManager.getInstance(this).getLocations(input), true) {
		
			@Override
			public View newView(Context context, Cursor cursor, ViewGroup parent) {
				LayoutInflater viewInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View convertView = viewInflater.inflate(R.layout.listevent, parent, false);
				return convertView;
			}
		
			@Override
			public void bindView(View view, Context context, Cursor cursor) {
				TextView txtName = (TextView) view.findViewById(R.id.listEventName);
				TextView txtDate = (TextView) view.findViewById(R.id.listEventDate);
				if (txtName != null) {
					txtName.setText(DataManager.getName(cursor));                       
				}
				if(txtDate != null) {
					txtDate.setText("");          
				}				
			}
		};
	 }
	private CursorAdapter getAdapter(){
		return new CursorAdapter(this, null) {
		
			@Override
			public View newView(Context context, Cursor cursor, ViewGroup parent) {
				LayoutInflater viewInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View convertView = viewInflater.inflate(R.layout.listevent, parent, false);
				return convertView;
			}
		
			@Override
			public void bindView(View view, Context context, Cursor cursor) {
				TextView txtName = (TextView) view.findViewById(R.id.listEventName);
				TextView txtDate = (TextView) view.findViewById(R.id.listEventDate);
				if (txtName != null) {
					txtName.setText(DataManager.getName(cursor));                       
				}
				if(txtDate != null) {
					txtDate.setText(DataManager.getDate(cursor));     
				}				
			}
		};
	 }
	
	private class UpdateLocationList extends AsyncTask<Void, ArrayList<Integer>, ArrayList<Integer>> {
		Context myContext;
		
		public UpdateLocationList(Context context) {
			super();
			this.myContext = context;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected ArrayList<Integer> doInBackground(Void... params) {
			ArrayList<Integer> buildingsAround = null;
			Cursor cursor = null;
			while(!isCancelled()){
				if(locationoverlay.getLastFix() != null)
				{
					cursor = DataManager.getInstance(myContext).getLocations(-1, null);
					buildingsAround = new ArrayList<Integer>();
					Location loc = locationoverlay.getLastFix();
					Location loc2 = new Location("building location");
					
					if(cursor.moveToFirst())
					{	
						do
						{
							double lat = DataManager.getLatitude(cursor);
							double lon = DataManager.getLongitude(cursor);
							loc2.setLatitude(lat);
	      	      			loc2.setLongitude(lon);
	      	      			if(loc.distanceTo(loc2) <= (120 + DataManager.getProximityRadius(cursor)))
	      	      			{
	      	      				buildingsAround.add(DataManager.getID(cursor));
	      	      			}
						}while(cursor.moveToNext());
					}
					cursor.close();
				}
				publishProgress(buildingsAround);
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return buildingsAround;
		}

		@Override
		protected void onProgressUpdate(ArrayList<Integer>... values) {
			if(values[0] != null){
				stopManagingCursor(((CursorAdapter) locations.getAdapter()).getCursor());
				((CursorAdapter) locations.getAdapter()).changeCursor(DataManager.getInstance(myContext).getLocations(values[0]));
	        	startManagingCursor(((CursorAdapter) locations.getAdapter()).getCursor());
	        	int count = ((CursorAdapter) locations.getAdapter()).getCount();
	        	String eventsButtonText = count + " Locations";
	        	eventsButton.setText(eventsButtonText);
	        	if(count < 1) 
	        		notifDrawer.lock();
	        	else
	        		notifDrawer.unlock();
			}
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(ArrayList<Integer> result) {
			stopManagingCursor(((CursorAdapter) locations.getAdapter()).getCursor());
			((CursorAdapter) locations.getAdapter()).changeCursor(DataManager.getInstance(myContext).getLocations(result));
	        startManagingCursor(((CursorAdapter) locations.getAdapter()).getCursor());
	        int count = ((CursorAdapter) locations.getAdapter()).getCount();
        	String eventsButtonText = count + " Locations";
        	eventsButton.setText(eventsButtonText);
        	if(count < 1) 
        		notifDrawer.lock();
        	else
        		notifDrawer.unlock();
			super.onPostExecute(result);
		}
	}
}
